package com.simtop.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simtop.common.ServerResponse;
import com.simtop.pojo.ModelData;
import com.simtop.pojo.User;
import com.simtop.service.SwreadService;
import com.simtop.util.JwtUtil;
import com.simtop.util.convert.Convert;
import com.simtop.vo.MonitoringDataExcelVo;
import com.simtop.vo.ReportdataExcelVo;
import com.simtop.vo.Swread;
import com.simtop.vo.TypesState;
import org.apache.poi.ss.usermodel.Workbook;
import org.python.antlr.op.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("swread")
@CrossOrigin
public class SwreadController {
    @Autowired
    private SwreadService swreadService;
    /**
     * 查询/选项查询
     * */
    @PostMapping("findall")
    @ResponseBody
    public ServerResponse findAll(@RequestBody String data, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            Integer pageNum = jsonObject.getInteger("pageNum");
            Integer pageSize = jsonObject.getInteger("pageSize");
            if(StringUtils.isEmpty(pageNum) || pageNum == 0){
                pageNum = 1;
            }
            if(StringUtils.isEmpty(pageSize) || pageSize == 0){
                pageSize = 10;
            }
            PageHelper.startPage(pageNum,pageSize);
            Integer  coach=u.getId();
            String tameName = jsonObject.getString("tameName");
            String types = jsonObject.getString("types");
            Date readTimeBegin = jsonObject.getDate("beginTime");
            Date readTimeEnd = jsonObject.getDate("endTime");
            String order=jsonObject.getString("order");
            String column=jsonObject.getString("column");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String readTimeBegins = null;
            String readTimeEnds = null;
            if(readTimeBegin != null && readTimeEnd != null) {
                readTimeBegins = df.format(readTimeBegin);
                readTimeEnds = df.format(readTimeEnd);
                List<Swread> swreadall = swreadService.findall(tameName,types,readTimeBegins,readTimeEnds,column,order,coach);
                PageInfo<Swread> pageInfo = new PageInfo<Swread>(swreadall);
                return ServerResponse.createBySuccess("获取内容成功",pageInfo);
            }

            List<Swread> swreadList = swreadService.findall(tameName,types,readTimeBegins,readTimeEnds,column,order,coach);
            PageInfo<Swread> pageInfo = new PageInfo<Swread>(swreadList);
            return ServerResponse.createBySuccess("获取内容成功",pageInfo);
        }
        catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByError();
        }
    }
    /***
     * 删除/批量删除
     */
    @PostMapping("/deleteResources")
    @ResponseBody
    public ServerResponse deleteResources(@RequestBody String data, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject parse = JSONObject.parseObject(data);
        String id = parse.getString("id");
        Long[] arr = Convert.toLongArray(id);
        try{
            swreadService.deleteResources(arr);
            return ServerResponse.createBySuccess("删除内容成功");
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("删除失败");
        }
    }
    /***
     * 查询今日类型占比
     */
    @RequestMapping(value = "/selectTypes")
    @ResponseBody
    public ServerResponse selectTypes(HttpServletRequest request, HttpServletResponse response){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            Integer  coach=u.getId();
            TypesState selectTypes=  swreadService.selectTypes(coach);
            Map tj=new HashMap<>();
            tj.put("单人泳姿",selectTypes.getC0());
            tj.put("50米泳姿",selectTypes.getC1());
            tj.put("自定义时长泳姿",selectTypes.getC2());
            tj.put("自定义距离计时",selectTypes.getC3());
            return ServerResponse.createBySuccess(tj);
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("查询成绩内容失败");
        }
    }
    /***
     * 导出今日训练记录
     */
    @RequestMapping(value = "listSwsave",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse listSwsave(String id, HttpServletRequest  request , HttpServletResponse response) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        Integer  coach=u.getId();
        try {
            if(id == null){
                try {
                    //找到所有的学生
                    //    List<Swread> findAlldeviceListAllBystatus= apiService.findAlldeviceListAllBystatus2();
                    List<Swread> findSwread = swreadService.selectAll(coach);
                    ArrayList<ReportdataExcelVo> excelVos = new ArrayList<ReportdataExcelVo>();
                    for (Swread as:findSwread
                    ) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        ReportdataExcelVo reportdataExcelVo = new ReportdataExcelVo();
                        reportdataExcelVo.setId(as.getId());
                        reportdataExcelVo.setUser(as.getUser());
                        reportdataExcelVo.setUserId(as.getUserId());
                        reportdataExcelVo.setBeginTime(sdf.format(as.getBeginTime()));
                        reportdataExcelVo.setEndTime(sdf.format(as.getEndTime()));
                        reportdataExcelVo.setTeam(as.getTeam());
                        reportdataExcelVo.setTypes(as.getTypes());
                        reportdataExcelVo.setUsername(as.getUsername());
                        reportdataExcelVo.setUserTime(as.getUseTime() + "秒");
                        // reportdataExcelVo.setSllang(as.getSllAng());
                        // reportdataExcelVo.setCjlast(as.getCjLast());
                        reportdataExcelVo.setCj(as.getCj());
                        excelVos.add(reportdataExcelVo);
                    }
                    ExportParams exportParams = new ExportParams("泳道今日训练记录全部数据", "泳道今日训练记录全部数据");//设置sheet
                    Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ReportdataExcelVo.class, excelVos);//问好处填vo
                    //String fileName = new String("社群全部成绩数据".getBytes(), "UTF-8") + ".xls";//设置excel的名称后缀
                    //response.setContentType("application/vnd.ms-excel;charset=UTF-8");//类型
                    //response.setHeader("Content-Disposition", "attachment;filename=" + fileName);//设置响应头
                    //response.setCharacterEncoding("UTF-8");//格式
                    String exportFileName ="泳道今日训练记录全部数据.xlsx";
                    String fileNameURL = URLEncoder.encode(exportFileName, "UTF-8");
                    response.setHeader("Content-disposition", "attachment;filename="+fileNameURL+";"+"filename*=utf-8''"+fileNameURL);
                    //response.setContentType("application/vnd.ms-excel;charset=UTF-8");//类型
                    response.setContentType("application/vnd.ms-excel");
                    OutputStream os = response.getOutputStream();
                    workbook.write(os);//写入
                    os.flush();
                    try {
                        os.close();//关闭
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return ServerResponse.createBySuccess();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    return ServerResponse.createByError();
                }
            }
            String[] split = id.split(",");
            ArrayList<Integer> objects = new ArrayList<>();
            Arrays.stream(split).iterator();
            ArrayList<Integer> sqsyidlist = new ArrayList<>();
            Iterator<String> iterator = Arrays.stream(split).iterator();
            while (iterator.hasNext()) {
                String next = iterator.next();
                Integer i = Integer.valueOf(next);
                sqsyidlist.add(i);
            }
            List<Swread> selectAll2= swreadService.selectAll2(sqsyidlist,coach);
            ArrayList<ReportdataExcelVo> excelVos = new ArrayList<ReportdataExcelVo>();
            for (Swread as:selectAll2
            ) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                ReportdataExcelVo reportdataExcelVo = new ReportdataExcelVo();
                reportdataExcelVo.setId(as.getId());
                reportdataExcelVo.setUser(as.getUser());
                reportdataExcelVo.setUserId(as.getUserId());
                reportdataExcelVo.setBeginTime(sdf.format(as.getBeginTime()));
                reportdataExcelVo.setEndTime(sdf.format(as.getEndTime()));
                reportdataExcelVo.setTeam(as.getTeam());
                reportdataExcelVo.setUsername(as.getUsername());
                reportdataExcelVo.setTypes(as.getTypes());
                reportdataExcelVo.setUserTime(as.getUseTime() + "秒");
                // reportdataExcelVo.setSllang(as.getSllAng());
                // reportdataExcelVo.setCjlast(as.getCjLast());
                reportdataExcelVo.setCj(as.getCj());
                excelVos.add(reportdataExcelVo);

            }
            ExportParams exportParams = new ExportParams("泳道今日训练记录全部数据", "泳道今日训练记录全部数据");//设置sheet
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ReportdataExcelVo.class, excelVos);//问好处填vo
            //String fileName = new String("社群全部成绩数据".getBytes(), "UTF-8") + ".xls";//设置excel的名称后缀
            //response.setContentType("application/vnd.ms-excel;charset=UTF-8");//类型
            //response.setHeader("Content-Disposition", "attachment;filename=" + fileName);//设置响应头
            //response.setCharacterEncoding("UTF-8");//格式
            String exportFileName ="泳道今日训练记录全部数据.xlsx";
            String fileNameURL = URLEncoder.encode(exportFileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+fileNameURL+";"+"filename*=utf-8''"+fileNameURL);
            //response.setContentType("application/vnd.ms-excel;charset=UTF-8");//类型
            response.setContentType("application/vnd.ms-excel");
            OutputStream os = response.getOutputStream();
            workbook.write(os);//写入
            os.flush();
            try {
                os.close();//关闭
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ServerResponse.createBySuccess();
        } catch (Exception ex) {
            ex.printStackTrace();
            return ServerResponse.createByError();
        }
    }
    /***
     * 查询今日分数占比
     */
    @RequestMapping(value = "/selectScore")
    @ResponseBody
    public ServerResponse selectScore(HttpServletRequest request, HttpServletResponse response){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            Integer  coach=u.getId();
            TypesState selectScore=  swreadService.selectScore(coach);
            return ServerResponse.createBySuccess(selectScore);
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("查询成绩内容失败");
        }
    }
    /**
     * 根据学号查询/选项查询
     * */
    @PostMapping("findid")
    @ResponseBody
    public ServerResponse findid(@RequestBody String data, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            Integer pageNum = jsonObject.getInteger("pageNum");
            Integer pageSize = jsonObject.getInteger("pageSize");
            if(StringUtils.isEmpty(pageNum) || pageNum == 0){
                pageNum = 1;
            }
            if(StringUtils.isEmpty(pageSize) || pageSize == 0){
                pageSize = 10;
            }
            PageHelper.startPage(pageNum,pageSize);
            String tameName = jsonObject.getString("tameName");
            String types = jsonObject.getString("types");
            Date readTimeBegin = jsonObject.getDate("beginTime");
            Date readTimeEnd = jsonObject.getDate("endTime");
            String order=jsonObject.getString("order");
            String column=jsonObject.getString("column");
            Integer userId=u.getUserId();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String readTimeBegins = null;
            String readTimeEnds = null;
            if(readTimeBegin != null && readTimeEnd != null) {
                readTimeBegins = df.format(readTimeBegin);
                readTimeEnds = df.format(readTimeEnd);
                List<Swread> swreadall = swreadService.findid(tameName,types,readTimeBegins,readTimeEnds,column,order,userId);
                PageInfo<Swread> pageInfo = new PageInfo<Swread>(swreadall);
                return ServerResponse.createBySuccess("获取内容成功",pageInfo);
            }

            List<Swread> swreadList = swreadService.findid(tameName,types,readTimeBegins,readTimeEnds,column,order,userId);
            PageInfo<Swread> pageInfo = new PageInfo<Swread>(swreadList);
            return ServerResponse.createBySuccess("获取内容成功",pageInfo);
        }
        catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByError();
        }
    }
    /***
     * 根据学号查询类型占比
     */
    @RequestMapping(value = "/userTypes")
    @ResponseBody
    public ServerResponse userTypes(HttpServletRequest request, HttpServletResponse response){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            Integer userId=u.getUserId();
            TypesState userTypes=  swreadService.userTypes(userId);
            Map tj=new HashMap<>();
            tj.put("单人泳姿",userTypes.getC0());
            tj.put("50米泳姿",userTypes.getC1());
            tj.put("自定义时长泳姿",userTypes.getC2());
            tj.put("自定义距离计时",userTypes.getC3());
            return ServerResponse.createBySuccess(tj);
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("查询成绩内容失败");
        }
    }
    /***
     * 查询分数占比
     */
    @RequestMapping(value = "/userScore")
    @ResponseBody
    public ServerResponse userScore(HttpServletRequest request, HttpServletResponse response){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            Integer userId=u.getUserId();
            TypesState selectScore=  swreadService.userScore(userId);
            return ServerResponse.createBySuccess(selectScore);
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("查询成绩内容失败");
        }
    }
    /***
     * 导出我的训练记录
     */
    @RequestMapping(value = "userrlistSwsave",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse userlistSwsave(String id, HttpServletRequest  request , HttpServletResponse response) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        Integer userId=u.getUserId();
        try {
            if(id == null){
                try {
                    //找到所有的学生
                    //    List<Swread> findAlldeviceListAllBystatus= apiService.findAlldeviceListAllBystatus2();

                    List<Swread> findSwread = swreadService.userAll(userId);
                    ArrayList<ReportdataExcelVo> excelVos = new ArrayList<ReportdataExcelVo>();
                    for (Swread as:findSwread
                    ) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        ReportdataExcelVo reportdataExcelVo = new ReportdataExcelVo();
                        reportdataExcelVo.setId(as.getId());
                        reportdataExcelVo.setUser(as.getUser());
                        reportdataExcelVo.setUserId(as.getUserId());
                        reportdataExcelVo.setBeginTime(sdf.format(as.getBeginTime()));
                        reportdataExcelVo.setEndTime(sdf.format(as.getEndTime()));
                        reportdataExcelVo.setTeam(as.getTeam());
                        reportdataExcelVo.setTypes(as.getTypes());
                        reportdataExcelVo.setUsername(as.getUsername());
                        reportdataExcelVo.setUserTime(as.getUseTime() + "秒");
                        // reportdataExcelVo.setSllang(as.getSllAng());
                        // reportdataExcelVo.setCjlast(as.getCjLast());
                        reportdataExcelVo.setCj(as.getCj());
                        excelVos.add(reportdataExcelVo);
                    }
                    ExportParams exportParams = new ExportParams("我的泳道训练记录全部数据", "我的泳道训练记录全部数据");//设置sheet
                    Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ReportdataExcelVo.class, excelVos);//问好处填vo
                    //String fileName = new String("社群全部成绩数据".getBytes(), "UTF-8") + ".xls";//设置excel的名称后缀
                    //response.setContentType("application/vnd.ms-excel;charset=UTF-8");//类型
                    //response.setHeader("Content-Disposition", "attachment;filename=" + fileName);//设置响应头
                    //response.setCharacterEncoding("UTF-8");//格式
                    String exportFileName ="我的泳道训练记录全部数据.xlsx";
                    String fileNameURL = URLEncoder.encode(exportFileName, "UTF-8");
                    response.setHeader("Content-disposition", "attachment;filename="+fileNameURL+";"+"filename*=utf-8''"+fileNameURL);
                    //response.setContentType("application/vnd.ms-excel;charset=UTF-8");//类型
                    response.setContentType("application/vnd.ms-excel");
                    OutputStream os = response.getOutputStream();
                    workbook.write(os);//写入
                    os.flush();
                    try {
                        os.close();//关闭
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return ServerResponse.createBySuccess();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    return ServerResponse.createByError();
                }
            }
            String[] split = id.split(",");
            ArrayList<Integer> objects = new ArrayList<>();
            Arrays.stream(split).iterator();
            ArrayList<Integer> sqsyidlist = new ArrayList<>();
            Iterator<String> iterator = Arrays.stream(split).iterator();
            while (iterator.hasNext()) {
                String next = iterator.next();
                Integer i = Integer.valueOf(next);
                sqsyidlist.add(i);
            }
            List<Swread> selectAll2= swreadService.userAll2(sqsyidlist);
            ArrayList<ReportdataExcelVo> excelVos = new ArrayList<ReportdataExcelVo>();
            for (Swread as:selectAll2
            ) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                ReportdataExcelVo reportdataExcelVo = new ReportdataExcelVo();
                reportdataExcelVo.setId(as.getId());
                reportdataExcelVo.setUser(as.getUser());
                reportdataExcelVo.setUserId(as.getUserId());
                reportdataExcelVo.setBeginTime(sdf.format(as.getBeginTime()));
                reportdataExcelVo.setEndTime(sdf.format(as.getEndTime()));
                reportdataExcelVo.setTeam(as.getTeam());
                reportdataExcelVo.setTypes(as.getTypes());
                reportdataExcelVo.setUsername(as.getUsername());
                reportdataExcelVo.setUserTime(as.getUseTime() + "秒");
                // reportdataExcelVo.setSllang(as.getSllAng());
                // reportdataExcelVo.setCjlast(as.getCjLast());
                reportdataExcelVo.setCj(as.getCj());
                excelVos.add(reportdataExcelVo);

            }
            ExportParams exportParams = new ExportParams("我的泳道训练记录全部数据", "我的泳道训练记录全部数据");//设置sheet
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ReportdataExcelVo.class, excelVos);//问好处填vo
            //String fileName = new String("社群全部成绩数据".getBytes(), "UTF-8") + ".xls";//设置excel的名称后缀
            //response.setContentType("application/vnd.ms-excel;charset=UTF-8");//类型
            //response.setHeader("Content-Disposition", "attachment;filename=" + fileName);//设置响应头
            //response.setCharacterEncoding("UTF-8");//格式
            String exportFileName ="我的泳道训练记录全部数据.xlsx";
            String fileNameURL = URLEncoder.encode(exportFileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+fileNameURL+";"+"filename*=utf-8''"+fileNameURL);
            //response.setContentType("application/vnd.ms-excel;charset=UTF-8");//类型
            response.setContentType("application/vnd.ms-excel");
            OutputStream os = response.getOutputStream();
            workbook.write(os);//写入
            os.flush();
            try {
                os.close();//关闭
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ServerResponse.createBySuccess();
        } catch (Exception ex) {
            ex.printStackTrace();
            return ServerResponse.createByError();
        }
    }
}
